<template>
  <div class="project">
    <ListTab v-model="activeId" :tabs="tabList" :show-header="!showMobilePage" is-table @tabClick="handleTabClick" />
    <div :class="{'mobile-table':showMobilePage}" class="table-list min-fill-page">
      <DataDisplay
        :data-list="statisticsList"
        class="mb16 mobile-data"
      />
      <div v-if="!showMobilePage" class="relative mb16 filter">
        <FilterInput ref="FilterToolRef" v-model="paramsObj" :is-show-filter="isShowFilter" :filter-list="filterList" show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
        <div class="table-top-opeator-bar">
          <createBtn v-if="hasRouteAuth('crm:inputInvoice:add')" style="margin-right:14px;" @click.native="handleCreate" />
          <MoreOpeator
            v-if="[1].includes(activeId) && hasRouteAuth('crm:inputInvoice:submit')"
            :list="[
              { label: '提交认证', handelClick: handleOperate, param: 0 },
              { label: '无需认证', handelClick: handleOperate, param: 1 }
            ]"
            style="margin-right:10px;"
          />
          <MoreOpeator
            v-if="[2].includes(activeId) && hasRouteAuth('crm:inputInvoice:confirm')"
            :list="[
              { label: '确认认证', handelClick: handleOperate, param: 2 },
              { label: '撤回待认证', handelClick: handleOperate, param: 3 }
            ]"
            style="margin-right:10px;"
          />
          <MoreOpeator
            v-if="[3].includes(activeId) && hasRouteAuth('crm:inputInvoice:withdraw')"
            :list="[{ label: '撤回', handelClick: handleOperate, param: 4 }]"
            style="margin-right:10px;"
          />
          <btnGroup
            ref="btnGroupRef"
            :list="[
              {label:'导入', importApi:'/admin/inputInvoice/import', callback: freshData, type: 'import', auth: hasRouteAuth('crm:inputInvoice:import') },
              {label:'导出', exportApi:'/admin/inputInvoice/export', exportName:'进项发票', beforeExport: exportBeforeExport, type: 'export'},
            ]"
          />
        </div>
      </div>
      <div v-loading="listLoading" class="table-wrap" style="min-height: 300px">
        <u-table
          v-if="list.items.length > 0"
          ref="inputInvoiceRef"
          :data="list.items"
          :row-class-name="tableRowClassName"
          :height="setTableHeight"
          :row-height="49"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @select="selectTable"
          @select-all="selectTable"
          @sort-change="sortMethod">
          <u-table-column
            :fixed="selectFixed"
            align="center"
            type="selection"
            width="50"/>
          <u-table-column align="left" label="发票类型" min-width="80">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.invoiceType | inputInvoiceType" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="发票号码" min-width="120" label-class-name="diy-cell" class-name="diy-cell">
            <template slot-scope="scope" slot="header">
              <div class="diyHeader">{{ scope.column.label }}</div>
            </template>
            <template slot-scope="scope">
              <processSn :is-expedited="scope.row.isExpedited">
                <div class="light-word" @click="toDetail(scope.row)">
                  <ToolTip :content="scope.row.invoiceNo" is-can-click @handelClick="toDetail(scope.row)"/>
                </div>
              </processSn>
            </template>
          </u-table-column>
          <u-table-column align="left" label="发票代码" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.invoiceCode" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="开票日期" min-width="120" prop="invoiceDate" sortable="custom">
            <template slot-scope="scope">
              <ToolTip :content="format(scope.row.invoiceDate, 'YYYY/MM/DD')" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="销方名称" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.sellerName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="销方税号" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.channelTaxId" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="发票项目" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.invoiceProject" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="含税金额(元)" min-width="130" prop="invoicePrice" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.invoicePrice" :price="scope.row.invoicePrice" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="税率" min-width="80">
            <template slot-scope="scope">
              <span v-if="scope.row.taxRate">{{ scope.row.taxRate }}%</span>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="实际销方名称" min-width="200">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.realChannelName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="购方名称" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.buyerName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="关联审批" min-width="130">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.approvalNumber" :open-delay="800" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px">
                  <div v-for="(item, index) in scope.row.withdraws" :key="index" style="cursor:pointer;" @click="toCheck(item)">{{ item.approvalNumber }}</div>
                </div>
                <div v-if="scope.row.withdraws.length > 1" class="light-word">共{{ scope.row.withdraws.length }}个审批单</div>
                <div v-else class="light-word ellipsis" @click="toCheckFirst(scope.row.withdraws)">{{ scope.row.approvalNumber }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="发票状态" min-width="80">
            <template slot-scope="scope">
              <StatusText
                v-if="scope.row.invoiceStatus || scope.row.invoiceStatus===0"
                :color="['#FFBC3D','#406EFF', '#31CC9C', '#999', '#31CC9C','#406EFF'][scope.row.invoiceStatus]"
                :text="scope.row.invoiceStatus | inputInvoiceStatus"
              />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="业务会计" min-width="80">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.businessAccounting" :label="scope.row.businessAccounting" :user-id="scope.row.businessAccountingId" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.creator" :label="scope.row.creator" :user-id="scope.row.creatorId" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属部门" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.department" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="跟进人" min-width="120">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.followUsers" :user-list="scope.row.followUsers" multiple label-name="userName"/>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="提交认证人" min-width="120">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.submitter" :label="scope.row.submitter" :user-id="scope.row.pushAuthenticatorId" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="执行认证人" min-width="120">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.executor" :label="scope.row.executor" :user-id="scope.row.execAuthenticatorId " />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column :width="operateWidth" fixed="right" align="left" label="操作">
            <template slot-scope="scope">
              <div v-if="!showMobilePage" style="display:flex">
                <div v-if="scope.row.status !== 0" class="button-text" @click="toDetail(scope.row)">查看</div>
                <el-dropdown trigger="click">
                  <div :class="{'border-left':scope.row.status !== 0}" class="el-dropdown-link">
                    <div class="button-text">更多<i class="el-icon-arrow-down"/></div>
                  </div>
                  <el-dropdown-menu
                    slot="dropdown"
                    class="dropdown-wrap">
                    <el-dropdown-item :disabled="setEditDisable(scope.row)" @click.native="handleEdit(scope.row)">
                      <div>编辑</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.invoiceStatus === 1" :disabled="setSubmitDisable(scope.row)" @click.native="handleOperate(0, '提交认证', scope.row.id)">
                      <div>提交认证</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.invoiceStatus === 1" :disabled="setSubmitDisable(scope.row)" @click.native="handleOperate(1, '无需认证', scope.row.id)">
                      <div>无需认证</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.invoiceStatus === 2" :disabled="setConfirmDisable(scope.row)" @click.native="handleOperate(2, '确认认证', scope.row.id)">
                      <div>确认认证</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.invoiceStatus === 2" :disabled="setConfirmDisable(scope.row)" @click.native="handleOperate(3, '撤回待认证', scope.row.id)">
                      <div>撤回待认证</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.invoiceStatus === 3" :disabled="setWithdrawDisable(scope.row)" @click.native="handleOperate(4, '撤回', scope.row.id)">
                      <div>撤回</div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <tableOperateBtn v-else>
                <el-dropdown-item v-if="scope.row.status !== 0" style="width:90px;text-align: center" @click.native="toDetail(scope.row)">
                  <div style="font-size: 14px">查看</div>
                </el-dropdown-item>
                <el-dropdown-item :disabled="setEditDisable(scope.row)" @click.native="handleEdit(scope.row)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.invoiceStatus === 1" :disabled="setSubmitDisable(scope.row)" @click.native="handleOperate(0, '提交认证', scope.row.id)">
                  <div>提交认证</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.invoiceStatus === 1" :disabled="setSubmitDisable(scope.row)" @click.native="handleOperate(1, '无需认证', scope.row.id)">
                  <div>无需认证</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.invoiceStatus === 2" :disabled="setConfirmDisable(scope.row)" @click.native="handleOperate(2, '确认认证', scope.row.id)">
                  <div>确认认证</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.invoiceStatus === 2" :disabled="setConfirmDisable(scope.row)" @click.native="handleOperate(3, '撤回待认证', scope.row.id)">
                  <div>撤回待认证</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.invoiceStatus === 3" :disabled="setWithdrawDisable(scope.row)" @click.native="handleOperate(4, '撤回', scope.row.id)">
                  <div>撤回</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!list.isInit"/>
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :is-show-filter="isShowFilter"
            :filter-list="filterList"
            show-mobile-icon
            show-search-btn
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus" />
          <createBtn v-if="hasRouteAuth('crm:inputInvoice:add')" mobile-table style="margin-right:14px;" @click.native="handleCreate" />
        </template>
        <template v-else>
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <div style="flex: 1;" />
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
// api
import { getDepartmentAll } from '@/api/config';
import ListTab from '@/components/ListTab';
import createBtn from '@/components/Common/baseComponent/createBtn';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import DataDisplay from '@/components/Common/baseComponent/dataDisplay';
import { standardFormat, format } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
// 跨页选中逻辑
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import isAdmin from '@/mixins/isAdmin';
import filterObjStoreMixin from '@/mixins/filterObjStore';
import { mapState } from 'vuex';
import { showModal } from '@/utils/message';
import { energyStatus, inputInvoiceStatus, inputInvoiceType } from '@/filters/status';
import { invoiceTypeOption } from './options';
import { getInputInvoiceTab, getInputInvoiceList, operateInputInvoice, getInputInvoiceStatistics } from '@/api/inputInvoice';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import icon_39 from '@/assets/dataDisplay/icon_39.png';
import icon_38 from '@/assets/dataDisplay/icon_38.png';
import icon_40 from '@/assets/dataDisplay/icon_43.png';
import icon_43 from '@/assets/dataDisplay/icon_40.png';
import icon_37 from '@/assets/dataDisplay/icon_37.png';

export default {
  components: {
    ListTab,
    EmptyPlaceholder,
    DataDisplay,
    MoreOpeator,
    createBtn,
    btnGroup
  },
  filters: { standardFormat, energyStatus, inputInvoiceStatus, inputInvoiceType },
  mixins: [
    tableSelections,
    isAdmin,
    TableAdaptive,
    mobileTable,
    filterObjStoreMixin
  ],
  data() {
    return {
      isUmyTable: true,
      tabList: [],
      activeId: -1,
      listLoading: false,
      page: 1,
      perPage: 20,
      sortName: '',
      sortType: '',
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      paramsObj: {},
      departmentOption: [],
      isShowFilter: false,
      tableRefName: 'inputInvoiceRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      ids: '',
      costId: 0,
      isBatch: 0,
      costIds: '',
      rangeKeyArr: [
        { attr: 'invoiceDate', start: 'invoiceDateStart', end: 'invoiceDateEnd', type: 'time', addTime: true },
        { attr: 'certifyDeductPeriod', start: 'certifyDeductPeriodStart', end: 'certifyDeductPeriodEnd', type: 'time', addTime: true },
        { attr: 'culturalConstructDeductPeriod', start: 'culturalConstructDeductPeriodStart', end: 'culturalConstructDeductPeriodEnd', type: 'time', addTime: true },
        { attr: 'taxTransferOutDate', start: 'taxTransferOutDateStart', end: 'taxTransferOutDateEnd', type: 'time', addTime: true },
        { attr: 'invoicePrice', start: 'invoicePriceStart', end: 'invoicePriceEnd', type: 'number' },
        { attr: 'taxRate', start: 'taxRateStart', end: 'taxRateEnd', type: 'number' },
        { attr: 'deductTaxAmount', start: 'deductTaxAmountStart', end: 'deductTaxAmountEnd', type: 'number' },
        { attr: 'taxTransferOut', start: 'taxTransferOutStart', end: 'taxTransferOutEnd', type: 'number' },
        { attr: 'deductAmount', start: 'deductAmountStart', end: 'deductAmountEnd', type: 'number' },
        { attr: 'nonCulturalConstructAmount', start: 'nonCulturalConstructAmountStart', end: 'nonCulturalConstructAmountEnd', type: 'number' }
      ],
      arrayKeyArr: ['department'],
      statusOption: [{ value: 0, label: '执行中' },
        { value: 1, label: '待认证' },
        { value: 2, label: '认证中' },
        { value: 3, label: '已完成' }],
      statisticsList: [
        { data: 0, label: '含税金额', icon: icon_39 },
        { data: 0, label: '抵扣税额', icon: icon_38 },
        { data: 0, label: '文建抵扣金额', icon: icon_43 },
        { data: 0, label: '进项税额转出', icon: icon_40 },
        { data: 0, label: '不可抵文建金额', icon: icon_37 }
      ]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    activeName() {
      const item = this.tabList.find(i => i.id === this.activeId);
      return item ? item.name : '全部';
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'invoiceNo', name: '发票号码', labelWidth: '100px', type: 'input' },
        { keyword: 'invoiceCode', name: '发票代码', labelWidth: '100px', type: 'input' },
        { keyword: 'sellerName', name: '销方名称', labelWidth: '100px', type: 'input' },
        { keyword: 'channelTaxId', name: '销方税号', labelWidth: '100px', type: 'input' },
        { keyword: 'invoiceProject', name: '发票项目', labelWidth: '100px', type: 'input' },
        { keyword: 'realChannelName', name: '实际销方名称', labelWidth: '100px', type: 'input' },
        { keyword: 'buyerName', name: '购方名称', labelWidth: '100px', type: 'input' },
        { keyword: 'approvalNumber', name: '关联审批', labelWidth: '100px', type: 'input' },
        { keyword: 'approvalCreator', name: '创建人', labelWidth: '100px', type: 'input' },
        { keyword: 'followUsersName', name: '跟进人', labelWidth: '100px', type: 'input' },
        { keyword: 'submitter', name: '提交认证人', labelWidth: '100px', type: 'input' },
        { keyword: 'executor', name: '执行认证人', labelWidth: '100px', type: 'input' },
        { keyword: 'businessAccounting', name: '业务会计', labelWidth: '100px', type: 'input' },
        { keyword: 'taxTransferOutReason', name: '进项税额转出原因', labelWidth: '100px', type: 'input' },
        // 范围
        { keyword: 'invoicePrice', name: '含税金额', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999 },
        { keyword: 'taxRate', name: '税率', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低税率', endPlaceholder: '最高税率', max: 999999999 },
        { keyword: 'deductTaxAmount', name: '抵扣税额', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999 },
        { keyword: 'taxTransferOut', name: '进项税额转出', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999 },
        { keyword: 'deductAmount', name: '文建抵扣金额', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999 },
        { keyword: 'nonCulturalConstructAmount', name: '不可抵文建金额', labelWidth: '100px', type: 'inputRange',
          isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999 },
        // 下拉
        { keyword: 'department', name: '所属部门', type: 'cascaderSelectWithChild', childrenVal: 'children',
          options: this.departmentOption },
        { keyword: 'invoiceType', name: '发票类型', type: 'select', options: invoiceTypeOption },
        { keyword: 'certificateStatus', name: '发票状态', type: 'select', options: this.statusOption },
        // 时间
        { keyword: 'invoiceDate', name: '开票日期', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'certifyDeductPeriod', name: '进项认证抵扣期', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'culturalConstructDeductPeriod', name: '文建抵扣期', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'taxTransferOutDate', name: '进项税额转出期', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 256 : 272;
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true
    }
  },
  created() {
    this.fetchData(true);
    this.queryDeptTreeList();
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'inputInvoiceDetail' || from.name === 'inputInvoiceEdit') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    if (!this.$route.meta.isChange) {
      this.paramsObj = {};
      this.isShowFilter = false;
      this.activeId = this.$route.query.tabStatus !== undefined ? Number(this.$route.query.tabStatus) : -1;
      this.fetchData(true);
      this.queryDeptTreeList();
    } else {
      // this.page = localStorage.getItem('projectPage');
      if (this.list && this.list.items && this.list.items.length === 0) {
        this.fetchData(true);
      } else {
        this.fetchData();
      }
    }
  },
  methods: {
    format,
    hasRouteAuth,
    // 获取部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.departmentOption = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    toCheck(item) {
      const url = this.$router.resolve({
        name: 'supplierDetail',
        query: {
          settleId: item.settleId,
          id: item.id,
          isSettle: true,
          fromInputInvoice: 1
        }
      });
      window.open(url.href, '_blank');
    },
    toCheckFirst(withdraws) {
      if (withdraws && withdraws.length > 0) {
        this.toCheck(withdraws[0]);
      }
    },
    formatParams(sendPageConfig = true) {
      const { page, perPage, activeId, paramsObj, activeName, sortName, sortType } = this;
      const params = JSON.parse(JSON.stringify(paramsObj));
      // 设置tab
      if (activeName !== '全部') params.tabStatus = activeId;
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      if (sendPageConfig) {
        params.page = page;
        params.perPage = perPage;
      }
      params.sortName = sortName || '';
      params.sortType = sortType || '';
      return params;
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.formatParams();
      this.getTabList(params);
      this.getStatisticsData(params);
      this.listLoading = true;
      getInputInvoiceList(params).then(({ data = {}} = {}) => {
        this.list = data;
      }).catch(e => {
        console.error(e);
      }).finally(() => {
        this.list.isInit = false;
        this.listLoading = false;
      });
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    // 获取顶部Tab列表
    async getTabList(params = {}) {
      try {
        const result = await getInputInvoiceTab(params);
        const { code, data = [] } = result;
        if (code === 200) {
          data.forEach((tab) => {
            tab.num = (tab.id === 3 ? 0 : tab.num);
          });
          this.tabList = data;
        }
      } catch (error) {
        this.tabList = [
          { id: -1, name: '全部', num: 0 },
          { id: 0, name: '执行中', num: 0 },
          { id: 1, name: '待认证', num: 0 },
          { id: 2, name: '认证中', num: 0 },
          { id: 3, name: '已完成', num: 0 }
        ];
        console.log(error);
      }
    },
    async getStatisticsData(params = {}) {
      try {
        const res = await getInputInvoiceStatistics(params);
        if (res.code === 200) {
          this.statisticsList = [
            { data: (res.data.invoicePrice / 100).toFixed(2), label: '含税金额', icon: icon_39 },
            { data: (res.data.deductTaxAmount / 100).toFixed(2), label: '抵扣税额', icon: icon_38 },
            { data: (res.data.deductAmount / 100).toFixed(2), label: '文建抵扣金额', icon: icon_43 },
            { data: (res.data.taxTransferOut / 100).toFixed(2), label: '进项税额转出', icon: icon_40 },
            { data: (res.data.nonCulturalConstructAmount / 100).toFixed(2), label: '不可抵文建金额', icon: icon_37 }
          ];
        }
      } catch (err) {
        console.log(err);
      }
    },
    setEditDisable(data) {
      return !([0, 1, 2].includes(data.invoiceStatus) && this.hasRouteAuth('crm:inputInvoice:edit'));
    },
    setSubmitDisable(data) {
      return !(data.invoiceStatus === 1 && this.hasRouteAuth('crm:inputInvoice:submit'));
    },
    setConfirmDisable(data) {
      return !(data.invoiceStatus === 2 && this.hasRouteAuth('crm:inputInvoice:confirm'));
    },
    setWithdrawDisable(data) {
      return !(data.invoiceStatus === 3 && this.hasRouteAuth('crm:inputInvoice:withdraw'));
    },
    handleTabClick(id) {
      this.activeId = id;
      this.fetchData(true);
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(perPage) {
      this.perPage = perPage;
      this.fetchData(true);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    toDetail(row) {
      this.$router.push({
        name: 'inputInvoiceDetail',
        query: { id: row.id }
      });
    },
    handleEdit(row) {
      this.$router.push({
        name: 'inputInvoiceEdit',
        query: { id: row.id }
      });
    },
    handleOperate(type, label, id) {
      const ids = id || this.multipleSelectionAll.map(item => item.id).join(',');
      // 提交认证
      showModal(`是否${label}?`, '', {
        iconClass: 'del-icon'
      }).then(() => {
        const params = { certificateType: type, ids };
        operateInputInvoice(params).then(res => {
          this.$message.success('操作成功');
          this.fetchData(true);
          this.clearMixinSelection();
        }).catch(err => { console.log(err); });
      }).catch(() => {
        return false;
      });
    },
    freshData() {
      this.fetchData(true);
    },
    exportBeforeExport() {
      const params = this.formatParams();
      if (this.multipleSelectionAll.length) {
        params.ids = this.multipleSelectionAll.map(el => el.id).join(',');
      }
      if (this.$refs.btnGroupRef) {
        this.$refs.btnGroupRef.btnExport(params);
      }
    },
    handleCreate() {
      this.$router.push({ name: 'inputInvoiceAdd' });
    }
  }
};
</script>
<style lang="scss" scoped>
@import '@/styles/placeholder.scss';
.dot-wrap {
  @extend %dot-wrap;
}
$bgc: #FFBC3D 0, #FD8546 1, #FF4E5F 2, #999 3, #31CC9C 4, #406EFF 5;
.project {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    .filter{
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      position: relative;
    }
    .border-left {
      position: relative;
      padding-left:6px;
      margin-left: 6px;
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        margin-top: -7px;
        width: 1px;
        background: #ddd;
        height: 14px;
      }
    }
    .dot {
      width: 4px;
      height: 4px;
      border-radius: 50%;
      margin-right: 5px;
      @each $c, $i in $bgc {
        &.color-#{$i} {
          background: $c;
        }
      }
    }
  }
}
.dropdown-wrap {
  margin-top: -24px;
  margin-right: 15px;
  padding: 0;
  .el-dropdown-menu__item {
    width: 100px;
    text-align: center;
  }
}
.light-word {
  color: #406eff;
  cursor: pointer;
}
</style>
<style lang="scss">
.el-dropdown-menu-batch-set.cost-dropdown {
  margin-bottom: 5px;
  padding: 0;
  .el-dropdown-menu__item {
    padding: 0 10px;
    min-width: 100px;
    max-width: 200px;
    text-align: center;
  }
  .meidum-export-btn {
    margin-right: 0px;
    height: 36px;
    color: inherit;
    background: none;
  }
}
</style>
